package com.nowcoder.community.controller;/**
 * 功能描述
 *
 * @author 21775
 * @date 2022/09/29  16:36
 */

import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.ProducerEvent;
import com.nowcoder.community.utils.CommunityConstUtil;
import com.nowcoder.community.utils.CommunityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *@ClassName ShareController
 *@Description TODO 方向长图
 *@Author 21775
 *@Date 2022/9/29 16:36
 *@Version 1.0
 */
@Controller
@Slf4j
public class ShareController {
    @Resource
    private ProducerEvent producerEvent;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${qiniu.bucket.share.url}")
    private String shareBucketUrl;


    @GetMapping("/share")
    @ResponseBody
    public String share(String htmlUrl){
        // 文件名
        String fileName= CommunityUtil.getUUID();
        //异步生成长图
        Event event=new Event()
                .setTopic(CommunityConstUtil.TOPIC_SHARE)
                .setData("htmlUrl",htmlUrl)
                .setData("fileName",fileName)
                .setData("suffix",".png");
        producerEvent.fireEvent(event);

        Map<String,Object> map=new HashMap<>();
//        map.put("shareUrl",domain+contextPath+"/share/image/"+fileName);
        map.put("shareUrl",shareBucketUrl+"/"+fileName);

        return CommunityUtil.getJSONString(0,null,map);
    }

    // 废弃
    @GetMapping("/share/image/{fileName}")
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response){
        if (StringUtils.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名不能为空!");
        }

        response.setContentType("image/png");
        File file = new File(wkImageStorage + "/" + fileName + ".png");
        try {
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            log.error("获取长图失败: " + e.getMessage());
        }

    }
}
